#include "customlistview.h"

#include <QKeyEvent>
#include <qDebug>

CustomListView::CustomListView (QObject *parent) {}



void CustomListView::keyPressEvent(QKeyEvent *event) {
    QModelIndex currentIndex = this->currentIndex();
    int rowCount = model()->rowCount();

    if (event->key() == Qt::Key_Tab) {
        if (currentIndex.isValid()) {
            int currentRow = currentIndex.row();
            // 如果当前行是最后一行，选中第一行
            if (currentRow + 1 < rowCount) {
                setCurrentIndex(model()->index(currentRow + 1, 0));
            } else {
                setCurrentIndex(model()->index(0, 0)); // 回到第一项
            }
            printCurrentItem();
        }
        event->accept();
    } else if ((event->key() == Qt::Key_Backtab) ||
               (event->key() == Qt::Key_Tab && event->modifiers() & Qt::ShiftModifier)) {
        if (currentIndex.isValid()) {
            int currentRow = currentIndex.row();
            // 如果当前行是第一行，选中最后一行
            if (currentRow > 0) {
                setCurrentIndex(model()->index(currentRow - 1, 0));
            } else {
                setCurrentIndex(model()->index(rowCount - 1, 0)); // 跳转到最后一项
            }
            printCurrentItem();
        }
        event->accept();
    } else {
        QListView::keyPressEvent(event);
    }
}

void CustomListView::printCurrentItem() {
    QModelIndex currentIndex = this->currentIndex();
    if (currentIndex.isValid()) {
        QString currentItemText = currentIndex.data(Qt::DisplayRole).toString();
        qDebug() << "当前选中项的内容:" << currentItemText;
    }

}
